C++ Interview Questions and Answers
Prepare for your Interview today!
Answer1.
"mutable" is a C++ keyword. When we declare const, none of its data members can change. When we want one of its members to change, we declare it as mutable.
Answer2.
A "mutable" keyword is useful when we want to force a "logical const" data member to have its value modified. A logical const can happen when we declare a data member as non-const, but we have a const member function attempting to modify that data member. For example:
class Dummy {
public:
bool isValid() const;
private:
mutable int size_ = 0;
mutable bool validStatus_ = FALSE;
// logical const issue resolved
};
bool Dummy::isValid() const
// data members become bitwise const
{
if (size > 10) {
validStatus_ = TRUE; // fine to assign
size = 0; // fine to assign
}
}
Answer2.
"mutable" keyword in C++ is used to specify that the member may be updated or modified even if it is member of constant object. Example:
class Animal {
private:
string name;
string food;
mutable int age;
public:
void set_age(int a);
};
void main() {
const Animal Tiger(â??Fulffyâ??,'antelopeâ??,1);
Tiger.set_age(2);
// the age can be changed since its mutable
}
In C, if you can a const variable e.g.
const int i = 2;
you can use this variable in other module as follows
extern const int i;
C compiler will not complain.
But for C++ compiler u must write
extern const int i = 2;
else error would be generated.
output = (X & Y) | (X & Z) | (Y & Z);
A modifier, also called a modifying function is a member function that changes the value of at least one data member. In other words, an operation that modifies the state of an object. Modifiers are also known as ?mutators?. Example: The function mod is a modifier in the following code snippet:
class test
{
int x,y;
public:
test()
{
x=0; y=0;
}
void mod()
{
x=10;
y=15;
}
};
An accessor is a class operation that does not modify the state of an object. The accessor functions need to be declared as const operations
Most helpful rated by users: